<template>
  <a-drawer
    title="修改用户"
    :maskClosable="false"
    width=650
    placement="right"
    :closable="false"
    @close="onClose"
    :visible="userEditVisiable"
    style="height: calc(100% - 55px);overflow: auto;padding-bottom: 53px;">

    <a-tabs defaultActiveKey="2" size="small">
      <a-tab-pane key="1">
      <span slot="tab">
        <a-icon type="android"/>
        账户信息
      </span>
        <a-form :form="form">
          <a-form-item label='登录名称' v-bind="formItemLayout">
            <a-input v-decorator="[
        'accountCode',
        { rules: [{ required: true, message: '请输入登录名称!' }] }
        ]"/>
          </a-form-item>
<!--          <a-form-item label='登录密码' v-bind="formItemLayout">-->
<!--            <a-input-password-->
<!--              v-decorator="[-->
<!--          'accountPwd',-->
<!--          { rules: [{ required: true, message: '请输入密码!' }] },-->
<!--        ]"/>-->
<!--          </a-form-item>-->
          <a-form-item label="显示名称" v-bind="formItemLayout">
            <a-input v-decorator="['accountName']"/>
          </a-form-item>
<!--          <a-form-item label='到期时间' v-bind="formItemLayout">-->
<!--            <a-date-picker v-decorator="[-->
<!--          'expireDate',-->
<!--          { rules: [{ required: true, message: '请选择过期时间!' }] },-->
<!--        ]"/>-->
<!--          </a-form-item>-->
          <a-form-item label='默认系统' v-bind="formItemLayout">
            <a-select  v-decorator="[
              'defaultApp',
              { rules: [{ required: true, message: '请输入默认系统!' }] }
              ]">
              <a-select-option v-for="appInfo in appInfoData" :key="appInfo.appId">
                {{appInfo.appName}}
              </a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item label='状态' v-bind="formItemLayout">
            <a-radio-group
              v-decorator="[
            'accountStatus',
            {rules: [{ required: true, message: '请选择状态' }]}
          ]">
              <a-radio value="0">有效</a-radio>
              <a-radio value="1">锁定</a-radio>
            </a-radio-group>
          </a-form-item>

        </a-form>
      </a-tab-pane>

      <a-tab-pane key="2">
      <span slot="tab">
        <a-icon type="android"/>
        所属系统
      </span>
        <a-transfer
          style="margin: 0 auto"
          :dataSource="mockData"
          :listStyle="{
            width: '45%',
            height: '500px',
          }"
          showSearch
          :filterOption="filterOption"
          :targetKeys="targetKeys"
          @change="handleChange"
          @search="handleSearch"
          :render="item=>item.title"
        >
        </a-transfer>
      </a-tab-pane>

      <a-tab-pane key="3">
      <span slot="tab">
        <a-icon type="android"/>
        拥有角色
      </span>
        <a-transfer
          style="margin: 0 auto"
          :dataSource="roleInfoData"
          :listStyle="{
            width: '45%',
            height: '500px',
          }"
          showSearch
          :filterOption="filterOption"
          :targetKeys="roleKeys"
          @change="handleChanges"
          @search="handleSearch"
          :render="item=>item.title"
        >
        </a-transfer>
      </a-tab-pane>

      <a-tab-pane key="4">
      <span slot="tab">
        <a-icon type="android"/>
        拥有权限(无效)
      </span>
        <a-directory-tree checkable multiple defaultExpandAll @select="onSelect" @check="onCheck">
          <a-tree-node :title="menu.menuName" :key="menu.menuCode" v-for="menu in menuInfoData">
            <a-tree-node :title="menuSon.menuName" :key="menuSon.menuCode" isLeaf v-if="menu.menuInfos.size!=0" v-for="menuSon in menu.menuInfos"/>
          </a-tree-node>
        </a-directory-tree>
      </a-tab-pane>
    </a-tabs>

    <div class="drawer-bootom-button">
      <a-popconfirm title="确定放弃编辑？" @confirm="onClose" okText="确定" cancelText="取消">
        <a-button style="margin-right: .8rem">取消</a-button>
      </a-popconfirm>
      <a-button @click="handleSubmit" type="primary" :loading="loading">提交</a-button>
    </div>
  </a-drawer>
</template>
<script>
  import {mapState, mapMutations} from 'vuex'

  const formItemLayout = {
    labelCol: {span: 3},
    wrapperCol: {span: 18}
  }
  export default {
    name: 'UserEdit',
    props: {
      userEditVisiable: {
        default: false
      }
    },
    data() {
      return {
        formItemLayout,
        account: {},
        form: this.$form.createForm(this),
        deptTreeData: [],
        roleData: [],
        userDept: [],
        mockData: [],
        targetKeys: [],
        appInfoData: [],
        roleInfoData: [],
        roleKeys: [],
        menuInfoData: [],
        userId: '',
        loading: false
      }
    },
    computed: {
      ...mapState({
        currentUser: state => state.account.user
      })
    },
    created() {
      //this.getMock();
      this.getAppInfo();
      this.getRoleInfo();
      this.getMenuInfo();
    },
    methods: {
      ...mapMutations({
        setUser: 'account/setUser'
      }),
      onClose() {
        this.loading = false
        this.form.resetFields()
        this.$emit('close')
      },
      setFormValues({...user}) {
        this.userId = user.accountId
        console.log(JSON.stringify(user));
        this.getMessageByAccount(user.accountId);
        user.accountStatus = user.accountStatus.toString();
        let fields = ['accountCode', 'accountName', 'defaultApp', 'accountStatus']
        Object.keys(user).forEach((key) => {
          if (fields.indexOf(key) !== -1) {
            this.form.getFieldDecorator(key)
            let obj = {}
            obj[key] = user[key]
            this.form.setFieldsValue(obj)
          }
        })
        if (user.roleId) {
          this.form.getFieldDecorator('roleId')
          let roleArr = user.roleId.split(',')
          this.form.setFieldsValue({'roleId': roleArr})
        }
        if (user.deptId) {
          this.userDept = [user.deptId]
        }
      },
      onDeptChange(value) {
        this.userDept = value
      },
      handleSubmit() {
        this.form.validateFields((err, values) => {
          if (!err) {
            this.loading = true
            let user = this.form.getFieldsValue()
            user.accountId = this.userId;
            this.$put('/power/account-info/accountInfoEdit', {
              appId: this.targetKeys.join(','), roleId: this.roleKeys.join(','),...user
            }).then((r) => {
              this.loading = false
              this.$emit('success')

            }).catch(() => {
              this.loading = false
            })
          }
        })
      },
      getAppInfo() {
        const targetKeys = [];
        const mockData = [];
        this.$get('/power/app-info').then((r) => {
          r.data.data.forEach(app => {
            const data = {
              key: app.appId.toString(),
              title: app.appName.toString(),
              description: app.appDescription,
              chosen: false,
            };
            if (data.chosen) {
              targetKeys.push(data.key);
            }
            mockData.push(data);
          })
          this.appInfoData = r.data.data;
        })
        this.mockData = mockData;
        this.targetKeys = targetKeys;
      },
      getRoleInfo() {
        const targetKeys = [];
        const mockData = [];
        this.$get('/power/role-info').then((r) => {
          r.data.data.forEach(role => {
            const data = {
              key: role.roleId.toString(),
              title: role.roleName.toString(),
              description: role.roleDescription,
              chosen: false,
            };
            if (data.chosen) {
              targetKeys.push(data.key);
            }
            mockData.push(data);
          })
        })
        this.roleInfoData = mockData;
        this.roleKeys = targetKeys;
      },
      getMenuInfo() {
        this.$get('/power/menu-info').then((r) => {
          this.menuInfoData = r.data.data;
        })
      },
      filterOption(inputValue, option) {
        return option.description.indexOf(inputValue) > -1;
      },
      handleChange(targetKeys, direction, moveKeys) {
        console.log(targetKeys, direction, moveKeys);
        this.targetKeys = targetKeys;
      },
      handleChanges(targetKeys, direction, moveKeys) {
        this.roleKeys = targetKeys;
      },
      handleSearch(dir, value) {
        console.log('search:', dir, value);
      },
      onSelect(keys) {
        console.log('Trigger Select', keys);
      },
      onCheck(checkedKeys, e) {
        console.log(JSON.stringify(checkedKeys));
      },
      getMessageByAccount(accountId) {
        this.$get('/power/account-info/getMessageByAccount/'+accountId).then((r) => {
          if(r.data.accountBindAppInfo!=undefined){
           this.targetKeys = r.data.accountBindAppInfo;
          }
          if(r.data.accountBindRoleInfo!=undefined){
            this.roleKeys = r.data.accountBindRoleInfo;
          }
        })
      }
    },
    watch: {
      userEditVisiable() {
        if (this.userEditVisiable) {
          this.$get('role').then((r) => {
            this.roleData = r.data.rows
          })
          this.$get('dept').then((r) => {
            this.deptTreeData = r.data.rows.children
          })
        }
      }
    }
  }
</script>
